// Modules to control application life and create native browser window
const { app, BrowserWindow, ipcMain, shell } = require('electron');
const path = require('node:path');
const fs = require('fs');
const { nativeImage } = require('electron');
const shortcuts = require('windows-shortcuts'); // 新增：引入 windows-shortcuts 模块

let mainWindow; // 保存主窗口引用

function createWindow() {
    mainWindow = new BrowserWindow({
        resizable: true, // 是否支持调整窗口大小
        icon: './portal/favicon.ico', // 左上角图标
        minWidth: 1200,
        minHeight: 800,
        frame: false,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
            fullscreen: true,
            devTools: true, // 是否允许打开调试模式
            webSecurity: false, // 禁用安全策略
            nodeIntegration: true, // 5.x以上版本，默认无法在渲染进程引入node模块，需要这里设置为true
            cache: false,  // 禁用缓存
            partition: 'persist:no-cache'  // 使用独立会话分区
        }
    });

    // 加载 index.html
    mainWindow.loadFile('./pages/index.html');

    // 监听窗口拖拽事件
    ipcMain.on('window-drag', (event, { offsetX, offsetY }) => {
        const [x, y] = mainWindow.getPosition();
        mainWindow.setPosition(x + offsetX, y + offsetY);
    });

    // 新增：获取窗口位置
    ipcMain.on('get-window-position', () => {
        const [x, y] = mainWindow.getPosition();
        mainWindow.webContents.send('window-position', { x, y });
    });

    // 新增：支持窗口最大化、最小化和关闭
    ipcMain.on('window-maximize', () => {
        if (mainWindow.isMaximized()) {
            mainWindow.unmaximize();
        } else {
            mainWindow.maximize();
        }
    });

    ipcMain.on('window-minimize', () => {
        mainWindow.minimize();
    });

    ipcMain.on('window-close', () => {
        mainWindow.close();
    });

    // 新增：监听渲染进程请求应用列表
    ipcMain.handle('get-apps', () => {
        return getLocalApps();
    });

    // 新增：监听渲染进程请求打开应用
    ipcMain.on('open-app', (event, appPath) => {
        try {
            // Handle .lnk shortcuts differently
            if (appPath.endsWith('.lnk')) {
                shortcuts.query(appPath, (err, target) => {
                    if (err) {
                        console.error('Failed to resolve shortcut:', err);
                        return;
                    }
                    // console.log('Resolved shortcut target:', target);
                    shell.openPath(target.target)
                    // .then(() => console.log(`Successfully opened: ${target}`))
                    // .catch(error => console.error(`Failed to open: ${target}`, error));
                });
            } else {
                // For direct .exe files
                shell.openPath(appPath)
                // .then(() => console.log(`Successfully opened: ${appPath}`))
                // .catch(error => console.error(`Failed to open: ${appPath}`, error));
            }
        } catch (error) {
            console.error('Error occurred while opening app:', error);
        }
    });

}

// 获取本地应用列表
function getLocalApps() {
    const apps = [];
    const appPaths = new Set(); // 新增：用于存储已添加的应用路径，避免重复
    const desktopPath = path.join(process.env.USERPROFILE, 'Desktop'); // 动态获取桌面路径
    console.log('desktopPath:', desktopPath);
    // 遍历公共桌面路径
    const publicAppPath = 'C:\\Users\\Public\\Desktop';
    console.log('publicAppPath:', publicAppPath);
    // 遍历系统应用路径
    const systemAppPath = 'C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs';
    console.log('systemAppPath:', systemAppPath);
    const paths = ['E:\\Desktop', desktopPath, publicAppPath, systemAppPath]
    paths.forEach(appPath => {
        fs.readdirSync(appPath).forEach(file => {
            const filePath = path.join(appPath, file);
            if (file.endsWith('.exe') || file.endsWith('.lnk')) {
                const iconName = file.replace(/\.(exe|lnk)$/, '');
                if (!appPaths.has(iconName)) { // 检查是否已添加
                    appPaths.add(iconName);
                    apps.push({
                        name: iconName,
                        path: filePath,
                    });
                }
            }
        });
    })

    return apps;
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
    createWindow()

    app.on('activate', function () {
        // On macOS it's common to re-create a window in the app when the
        // dock icon is clicked and there are no other windows open.
        if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
    if (process.platform !== 'darwin') app.quit()
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.